#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using FreeOnlineApplication.Class.Entity;
using FreeOnlineApplication.Class.Repository;

#endregion

namespace FreeOnlineApplication
{
    public partial class FacilityTransactionUserControl : UserControl, IChildForm
    {
        FacilityRepository m_repFacility;
        CheckInRepository m_repCheckIn;
        FacilityTransactionRepository m_rep;
        FacilityTransaction m_subject = new FacilityTransaction();
        IMainForm m_mainForm;
        string DECIMAL_FORMAT = "###,###,###,###,###,###,###,##0.00";

        public FacilityTransactionUserControl(string name, IMainForm mainform)
        {
            InitializeComponent();
            m_repFacility = new FacilityRepository(mainform.Connection);
            m_repCheckIn = new CheckInRepository(mainform.Connection);
            m_rep = new FacilityTransactionRepository(mainform.Connection);

            InitializeButtonClick();
            m_mainForm = mainform;
            this.Name = name;
            this.Dock = DockStyle.Fill;
            //loadRecords();
            InitDataGridRows();
            InitEvent();
            ClearForm();
            setEditMode(EditMode.New);
        }

        private void InitEvent()
        {
            dataGridViewItems.CellValidated += new DataGridViewCellEventHandler(dataGridViewItems_CellValidated);
            dataGridViewItems.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridViewItems_CellValidating);
        }

        private void InitDataGridRows()
        {
            IList codes = m_repFacility.GetAllCodes(m_mainForm.CurrentUnit.ID);
            ((DataGridViewComboBoxColumn)dataGridViewItems.Columns[facilityDataGridViewComboBoxColumn1.Index]).DataSource = codes;
            IList checkInOpen = m_repCheckIn.GetAllOpen(m_mainForm.CurrentUnit.ID);
            comboBoxCheckIn.DataSource = checkInOpen;
        }

        void dataGridViewItems_CellValidated(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == facilityDataGridViewComboBoxColumn1.Index)
            {
                if (dataGridViewItems[facilityDataGridViewComboBoxColumn1.Index, e.RowIndex].Value == null) return;
                string code = dataGridViewItems[facilityDataGridViewComboBoxColumn1.Index, e.RowIndex].Value.ToString();
                Facility fac = m_repFacility.GetByCode(code.Split(':')[0].Trim(), m_mainForm.CurrentUnit.ID);

                dataGridViewItems[descriptionDataGridViewTextBoxColumn1.Index, e.RowIndex].Value = fac == null ? "" : fac.NAME;
                dataGridViewItems[priceDataGridViewTextBoxColumn1.Index, e.RowIndex].Value = fac == null ? 0 : fac.SERVICE_PRICE;
                calculateTotal();
            }
            if (e.ColumnIndex == qtyDataGridViewTextBoxColumn1.Index)
                calculateTotal();
            if (e.ColumnIndex == priceDataGridViewTextBoxColumn1.Index)
                calculateTotal();
        }

        private void calculateTotal()
        {
            decimal total = 0;
            for (int i = 0; i < dataGridViewItems.Rows.Count; i++)
            {
                try
                {
                    decimal price = dataGridViewItems[priceDataGridViewTextBoxColumn1.Index, i] == null ? 0 : Convert.ToDecimal(dataGridViewItems[priceDataGridViewTextBoxColumn1.Index, i].Value);
                    decimal qty = dataGridViewItems[qtyDataGridViewTextBoxColumn1.Index, i] == null ? 0 : Convert.ToDecimal(dataGridViewItems[qtyDataGridViewTextBoxColumn1.Index, i].Value);
                    decimal subtotal = price * qty;
                    dataGridViewItems[subTotaldataGridViewTextBoxColumn1.Index, i].Value = subtotal;
                    total += subtotal;
                }
                catch (Exception x)
                { 
                }
            }
            numericUpDownTotalPrice.Value = total;
        }

        void dataGridViewItems_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            dataGridViewItems.Rows[e.RowIndex].ErrorText = "";
            if ((e.ColumnIndex == qtyDataGridViewTextBoxColumn1.Index)
                ||(e.ColumnIndex == priceDataGridViewTextBoxColumn1.Index))
            {
                decimal output;
                if (!decimal.TryParse(e.FormattedValue.ToString(), out output))
                {
                    dataGridViewItems.Rows[e.RowIndex].ErrorText = "ketik angka";
                    e.Cancel = true;
                }
            }
        }

        private void InitializeButtonClick()
        {
            toolBarButtonSave.Click += new EventHandler(buttonSave_Click);
            toolBarButtonEdit.Click += new EventHandler(buttonEdit_Click);
            toolBarButtonDelete.Click += new EventHandler(buttonDelete_Click);
            toolBarButtonClear.Click += new EventHandler(buttonClear_Click);
            toolBarButtonCancel.Click += new EventHandler(toolBarButtonCancel_Click);
        }

        void toolBarButtonCancel_Click(object sender, EventArgs e)
        {
            ClearForm();
            setEditMode(EditMode.New);
        }
        public void ClearForm()
        {
            textBoxCode.Text = "FCTR" + (m_rep.GetCount(m_mainForm.CurrentUnit.ID) + 1).ToString().PadLeft(3, '0');
            numericUpDownTotalPrice.Value = 0;
            dataGridViewItems.Rows.Clear();
            
            m_subject = new FacilityTransaction();
            errorProvider.SetError(textBoxCode, "");
            errorProvider.SetError(numericUpDownTotalPrice, "");
        }
        public void setEnableForm(bool enable)
        {
            textBoxCode.Enabled = enable;
            numericUpDownTotalPrice.Enabled = enable;
            facilityDataGridViewComboBoxColumn1.ReadOnly = !enable;
            qtyDataGridViewTextBoxColumn1.ReadOnly = !enable;
            priceDataGridViewTextBoxColumn1.ReadOnly = !enable;
            dataGridViewItems.AllowUserToAddRows = enable;
            dataGridViewItems.AllowUserToDeleteRows = enable;
        }
        public bool Valid()
        {
            bool a = textBoxCode.Text == "";
            bool b = numericUpDownTotalPrice.Value < 1;
            bool c = comboBoxCheckIn.SelectedItem == null;
            CheckIn ch = (CheckIn)comboBoxCheckIn.SelectedItem;
            bool d = ch==null?true:!(ch.STATUS == "OPEN");

            if (a) errorProvider.SetError(textBoxCode, "Can not Empty");
            if (b) errorProvider.SetError(numericUpDownTotalPrice, "can not less then 0");
            if (c) errorProvider.SetError(comboBoxCheckIn, "Check In has to Open Status");
            if (d) errorProvider.SetError(comboBoxCheckIn, "Check In has to Open Status");
            return !a && !b && !c && !d;
        }
        private void setEditMode(EditMode editmode)
        {
            toolBarButtonSave.Enabled = editmode == EditMode.New || editmode == EditMode.Update;
            toolBarButtonEdit.Enabled = editmode == EditMode.View;
            toolBarButtonDelete.Enabled = editmode == EditMode.View;
            LoadEnableButton();
        }
        //private void loadRecords()
        //{
        //    listView1.Items.Clear();
        //    IList records = m_rep.GetAll(m_mainForm.CurrentUnit.ID);
        //    foreach (FacilityTransaction d in records)
        //    {
        //        ListViewItem item = listView1.Items.Add(d.CODE);
        //        item.SubItems.Add(d.NAME);
        //        item.SubItems.Add(d.SERVICE_PRICE.ToString(DECIMAL_FORMAT));
        //        item.Tag = d;
        //    }
        //}
        //private void removeRecord(int id)
        //{
        //    foreach (ListViewItem item in listView1.Items)
        //    {
        //        FacilityTransaction dep = (FacilityTransaction)item.Tag;
        //        if (dep.ID == id)
        //        {
        //            listView1.Items.Remove(item);
        //            break;
        //        }
        //    }
        //}
        private void UpdateEntity()
        {
            m_subject.CODE = textBoxCode.Text.Trim();
            m_subject.CHECK_IN = (CheckIn)comboBoxCheckIn.SelectedItem;
            m_subject.TOTAL_AMOUNT = Convert.ToDouble(numericUpDownTotalPrice.Value);
            m_subject.UNIT = m_mainForm.CurrentUnit;
            m_subject.FACILITY_ITEMS.Clear();
            foreach (DataGridViewRow r in dataGridViewItems.Rows)
            {
                FacilityTransactionItem itm = (FacilityTransactionItem)r.Tag;
                if (itm == null) itm = new FacilityTransactionItem();
                if (dataGridViewItems[facilityDataGridViewComboBoxColumn1.Index, r.Index].Value == null) continue;
                string code = dataGridViewItems[facilityDataGridViewComboBoxColumn1.Index, r.Index].Value.ToString();
                itm.FACILITY = m_repFacility.GetByCode(code.Split(':')[0].Trim(), m_mainForm.CurrentUnit.ID);
                itm.FACILITY_TRANSACTION = m_subject;
                if (dataGridViewItems[qtyDataGridViewTextBoxColumn1.Index, r.Index].Value == null) continue;
                itm.QUANTITY = Convert.ToDouble(dataGridViewItems[qtyDataGridViewTextBoxColumn1.Index, r.Index].Value);
                itm.PRICE = Convert.ToDouble(dataGridViewItems[priceDataGridViewTextBoxColumn1.Index, r.Index].Value);
                itm.SUB_AMOUNT = Convert.ToDouble(dataGridViewItems[subTotaldataGridViewTextBoxColumn1.Index, r.Index].Value);
                m_subject.FACILITY_ITEMS.Add(itm);
            }
        }
        private void buttonSave_Click(object sender, EventArgs e)
        {
            if (Valid())
            {
                UpdateEntity();
                if (m_subject.ID == 0)
                {
                    m_rep.Insert(m_subject);
                }
                else
                {
                    m_rep.Update(m_subject);
                }
                MessageBox.Show("Data telah tersimpan.");
                setEnableForm(false);
                setEditMode(EditMode.View);
                //ClearForm();
                //loadRecords();
            }
        }
        private void buttonEdit_Click(object sender, EventArgs e)
        {
            setEnableForm(true);
            setEditMode(EditMode.Update);
        }
        private void buttonClear_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Are sure to Clear?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, new EventHandler(clear));
        }
        private void clear(object obj, EventArgs e)
        {
            MessageBoxWindow w = (MessageBoxWindow)obj;
            if (w.DialogResult == DialogResult.Yes)
            {
                ClearForm();
                setEnableForm(true);
                setEditMode(EditMode.New);
            }
        }
        private void buttonDelete_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Delete record?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2, new EventHandler(delete));
        }
        private void delete(object obj, EventArgs e)
        {
            try
            {
                MessageBoxWindow w = (MessageBoxWindow)obj;
                if (w.DialogResult == DialogResult.Yes)
                {
                    if (m_subject.ID > 0)
                    {
                        m_rep.Delete(m_subject);
                        removeRecord(m_subject.ID);
                        ClearForm();
                        setEnableForm(true);
                        setEditMode(EditMode.New);
                    }
                }
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void removeRecord(int p)
        {
            foreach (ListViewItem itm in listView1.Items)
            {
                FacilityTransaction tr = (FacilityTransaction)itm.Tag;
                if (tr.ID == p)
                {
                    listView1.Items.Remove(itm);
                    return;
                }
            }
        }
        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 0) return;
            ClearForm();
            m_subject = (FacilityTransaction)listView1.SelectedItem.Tag;
            setEnableForm(false);
            loadData(m_subject);
            setEditMode(EditMode.View);
        }
        private void loadData(FacilityTransaction emp)
        {
            emp = m_rep.GetById(emp.ID);
            emp.CHECK_IN = m_repCheckIn.GetById(emp.CHECK_IN.ID);

            textBoxCode.Text = emp.CODE;
            comboBoxCheckIn.Text = emp.CHECK_IN.ToString();
            numericUpDownTotalPrice.Value = (decimal)emp.TOTAL_AMOUNT;

            foreach (FacilityTransactionItem itm in emp.FACILITY_ITEMS)
            {
                itm.FACILITY = m_repFacility.GetById(itm.FACILITY.ID);
                int t = dataGridViewItems.Rows.Add();
                dataGridViewItems.Rows[t].Tag = itm;
                dataGridViewItems[facilityDataGridViewComboBoxColumn1.Index, t].Value = itm.FACILITY.CODE + " : " + itm.FACILITY.NAME;
                dataGridViewItems[descriptionDataGridViewTextBoxColumn1.Index, t].Value = itm.FACILITY.NAME;
                dataGridViewItems[qtyDataGridViewTextBoxColumn1.Index, t].Value = itm.QUANTITY;
                dataGridViewItems[priceDataGridViewTextBoxColumn1.Index, t].Value = itm.PRICE;
                dataGridViewItems[subTotaldataGridViewTextBoxColumn1.Index, t].Value = itm.SUB_AMOUNT;
            }
        }

        #region IMainMenu Members

        public void Save()
        {
            buttonSave_Click(null, null);
        }

        public void New()
        {
            buttonClear_Click(null, null);
        }

        public void Delete()
        {
            buttonDelete_Click(null, null);
        }

        public void Edit()
        {
            buttonEdit_Click(null, null);
        }

        public void LoadEnableButton()
        {
            m_mainForm.SetEnableMenuButton(toolBarButtonSave.Enabled, toolBarButtonClear.Enabled,
            toolBarButtonDelete.Enabled, toolBarButtonEdit.Enabled);
        }

        #endregion

        private void buttonFind_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            IList records = m_rep.GetAllSearch(textBox1.Text.Trim(), m_mainForm.CurrentUnit.ID);
            if (records.Count == 0)
            {
                ListViewItem item = listView1.Items.Add("Data tidak di temukan");
            }
            foreach (FacilityTransaction d in records)
            {
                d.CHECK_IN = m_repCheckIn.GetById(d.CHECK_IN.ID);
                ListViewItem item = listView1.Items.Add(d.CODE);
                item.SubItems.Add(d.CODE);
                item.SubItems.Add(d.CHECK_IN.CODE);
                item.SubItems.Add(d.TOTAL_AMOUNT.ToString(DECIMAL_FORMAT));
                item.Tag = d;
            }
        }

    }
}